package me.dongcha.reggie402.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> excepionHander(SQLIntegrityConstraintViolationException e) {
        log.warn("异常信息:" + e.getMessage());
        if (e.getMessage().contains("Duplicate entry")) {
            String n = e.getMessage().split(" ")[2];
            return R.error("您输入的账号重复,请重新设置 " + n);
        } else if (e.getMessage().contains("cannot be null")) {
            String n = e.getMessage().split(" ")[1];
            return R.error("账号不能为空,请重新设置 " + n);
        }
        return R.error("未知错误,请联系管理员解决");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException e) {
        log.warn("[当前异常信息]:{}", e.getMessage());
        return R.error(e.getMessage());
    }
}
